package com.yhyvr.api.service.store;/**
 * Created by zhangqin on 2017/5/25.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.lz.kit.LogKit;
import com.lz.kit.Prop;
import com.lz.kit.PropKit;
import com.lz.kit.ehcache.CacheKit;
import com.lz.mybatis.jdbc.auto.dao.*;
import com.lz.mybatis.jdbc.auto.model.*;
import com.lz.tool.ListUtils;
import com.lz.tool.OkHttpUtil;
import com.lz.tool.SysProperties;
import com.lz.tool.date.DateStyle;
import com.lz.tool.date.DateUtil;
import com.tencent.WXPay;
import com.tencent.common.Signature;
import com.tencent.common.XMLParser;
import com.tencent.protocol.unifiedorder_protocol.UnifiedOrderReqData;
import com.tencent.protocol.unifiedorder_protocol.UnifiedOrderRespData;
import com.tencent.protocol.unifiedorder_protocol.jsapi.JsApiPayModel;
import com.yhyvr.api.service.wx.WxService;
import com.yhyvr.pojo.exception.ApiException;
import com.yhyvr.api.handle.AuthAnnotation;
import com.yhyvr.pojo.order.*;
import com.yhyvr.pojo.req.api.ApiReqData;
import com.yhyvr.pojo.req.api.store.order.*;
import com.yhyvr.pojo.resp.CommonResp;
import com.yhyvr.pojo.resp.HttpResult;
import com.yhyvr.pojo.resp.api.ApiRespBody;
import com.yhyvr.pojo.resp.api.ApiRespData;
import com.yhyvr.pojo.resp.api.ApiResultCode;
import com.yhyvr.pojo.resp.api.store.address.ApiOrderAddressResp;
import com.yhyvr.pojo.resp.api.store.order.ApiOrderGoodsResp;
import com.yhyvr.pojo.resp.api.store.order.ApiOrderInfoResp;
import com.yhyvr.pojo.resp.api.store.order.ApiOrderLogResp;
import com.yhyvr.service.ProxyOrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商城订单服务类
 *
 * @author
 * @create 2017-05-25 9:54
 **/
@Service
public class ApiOrderService {

    private static final Logger logger = LoggerFactory.getLogger(ApiOrderService.class);
    @Resource
    private BoCommentMapper boCommentMapper;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private ProxyOrderService orderService;
    @Resource
    private BoOrderLogMapper boOrderLogMapper;
@Resource
private WxService wxService;
    @Resource
    private BoProxyOrderMapper boProxyOrderMapper;
    @Resource
    private BoTasteGoodsMapper boTasteGoodsMapper;
    @Resource
    private BoProxyOrderGoodsMapper boProxyOrderGoodsMapper;
    @Resource
    private BoProxyMapper boProxyMapper;
    private static  final  String orderShellChannlCanPay= "1,2,3,4";
    @Resource
    private BoDictionaryMapper boDictionaryMapper;
    /**
     * 订单详情
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiOrderInfoResp> orderInfo(ApiReqData<ApiOrderInfoReq> apiReqData){
            ApiOrderInfoReq apiUnifiedorderReq = apiReqData.getBody();
                BoProxyOrderExample boProxyOrderExample = new BoProxyOrderExample();
                String orderId = apiUnifiedorderReq.getOrderId();
                boProxyOrderExample.createCriteria().andOrderIdEqualTo(orderId).andProxyIdEqualTo(apiReqData.getCookieUserId());
                BoProxyOrder boProxyOrder = ListUtils.getFirst(boProxyOrderMapper.selectByExample(boProxyOrderExample));
                //封装订单详情
                return ApiRespData.buildSucc(packOrderInfo(boProxyOrder));
    }

    /**
     * 订单详情
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<Boolean> isPaySuccess(ApiReqData<ApiOrderInfoReq> apiReqData){
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(apiReqData.getBody().getOrderId());
        if(boProxyOrder!=null){
            if(boProxyOrder.getOrderPayState()==1){
                return ApiRespData.buildSucc(true);
            }else{
                return ApiRespData.buildSucc(false);
            }
        }
        //封装订单详情
        return ApiRespData.buildFail();
    }

    /**
     * 订单列表
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<List<ApiOrderInfoResp>> orderList(ApiReqData<ApiOrderListReq> apiReqData){
                List<ApiOrderInfoResp> list = Lists.newArrayList();
        ApiOrderListReq apiOrderListReq = apiReqData.getBody();
                BoProxyOrderExample boProxyOrderExample = new BoProxyOrderExample();
                boProxyOrderExample.setOrderByClause("create_time desc");
        BoProxyOrderExample.Criteria criteria = boProxyOrderExample.createCriteria();
        criteria .andProxyIdEqualTo(apiReqData.getCookieUserId()).andDeleteOrderNotEqualTo(1);
        if(StringUtils.isNotBlank(apiOrderListReq.getOrderState())){
                    switch (apiOrderListReq.getOrderState()){
                        case "1":
                            break;
                        case "2":
                            criteria.andOrderPayStateEqualTo(0);
                            break;
                        case "3":
                            boProxyOrderExample.clear();
                            boProxyOrderExample.setOrderByClause("create_time desc");
                            boProxyOrderExample.or().andProxyIdEqualTo(apiReqData.getCookieUserId()).andDeleteOrderNotEqualTo(1).andOrderPayStateEqualTo(1).andOrderDeliveryStateEqualTo(1);
                            boProxyOrderExample.or().andProxyIdEqualTo(apiReqData.getCookieUserId()).andDeleteOrderNotEqualTo(1).andOrderPayStateEqualTo(1).andOrderDeliveryStateEqualTo(0);
                            break;
                        case "4":
                            criteria.andOrderPayStateEqualTo(1).andOrderDeliveryStateEqualTo(2);
                            break;
                        case "5":
                            criteria.andOrderPayStateEqualTo(2);
                            break;
                    }
                }
                List<BoProxyOrder>  boProxyOrders = boProxyOrderMapper.selectByExample(boProxyOrderExample);
                if(boProxyOrders!=null&&boProxyOrders.size()>0) {
                    for (BoProxyOrder boProxyOrder : boProxyOrders) {
                        list.add(packOrderInfo(boProxyOrder));
                    }
                }
                return ApiRespData.buildSucc(list);

    }
    /**
     * 删除订单
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiRespBody> deleteOrder(ApiReqData<ApiOrderInfoReq> apiReqData){
            ApiOrderInfoReq apiUnifiedorderReq = apiReqData.getBody();
            try {
                String orderId = apiUnifiedorderReq.getOrderId();
                BoProxyOrderExample boProxyOrderExample = new BoProxyOrderExample();
                boProxyOrderExample.createCriteria().andProxyIdEqualTo(apiReqData.getCookieUserId()).andOrderIdEqualTo(orderId);
                BoProxyOrder boProxyOrder =  ListUtils.getFirst(boProxyOrderMapper.selectByExample(boProxyOrderExample));
                if(boProxyOrder.getOrderPayState()==2||boProxyOrder.getOrderDeliveryState()==2) {
                    boProxyOrder.setDeleteOrder(1);
                    boProxyOrderMapper.updateByPrimaryKeySelective(boProxyOrder);
                }else{
                    throw new ApiException("订单不允许删除！",0,"10004",apiReqData.getHead().getCrossDomain());
                }
                return ApiRespData.buildSucc();
            } catch (Exception e) {
                throw new ApiException("删除失败，请刷新后重试！",0,apiReqData.getHead().getCrossDomain());
            }

    }

    /**
     * 下单二级分销
     */
    @Transactional
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiOrderInfoResp> unifiedorder(ApiReqData<ApiUnifiedorderReq> apiUnifiedorderReqApiReqData){
            ApiUnifiedorderReq apiUnifiedorderReq = apiUnifiedorderReqApiReqData.getBody();
            try {
                MakeERJIFENXIAOOrderReq makeERJIFENXIAOOrderReq = new MakeERJIFENXIAOOrderReq();
                makeERJIFENXIAOOrderReq.setBycard(false);
                makeERJIFENXIAOOrderReq.setGoodsId(apiUnifiedorderReq.getGoodsId());
                makeERJIFENXIAOOrderReq.setGoodsNumber(apiUnifiedorderReq.getGoodsNumber());
                makeERJIFENXIAOOrderReq.setShippingAddressId(apiUnifiedorderReq.getShippingAddressId());
                makeERJIFENXIAOOrderReq.setProxyId(apiUnifiedorderReqApiReqData.getCookieUserId());
                makeERJIFENXIAOOrderReq.setOrderType(2);
                HttpResult httpResult =  orderService.makeERJIFENXIAO(makeERJIFENXIAOOrderReq);
                if(httpResult.getHttp_status().equals("1")){
                    BoProxyOrder boProxyOrder = (BoProxyOrder) httpResult.getData();
                    return ApiRespData.buildSucc(packOrderInfo(boProxyOrder));
                }else{
                    return  ApiRespData.buildFail(ApiResultCode.FAIL,httpResult.getMessage());
                }

            } catch (Exception e) {
                LogKit.error(e.getMessage(),e);
                throw new ApiException(e.getMessage(),0,apiUnifiedorderReqApiReqData.getHead().getCrossDomain());
            }


    }


    /**
     * 下单二级分销购物车下单
     */
    @Transactional
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiOrderInfoResp> unifiedorderByCard(ApiReqData<ApiUnifiedorderByCardReq> apiUnifiedorderReqApiReqData){
        ApiUnifiedorderByCardReq apiUnifiedorderReq = apiUnifiedorderReqApiReqData.getBody();
        try {
            MakeERJIFENXIAOOrderReq makeERJIFENXIAOOrderReq = new MakeERJIFENXIAOOrderReq();
            makeERJIFENXIAOOrderReq.setBycard(true);
            makeERJIFENXIAOOrderReq.setShippingAddressId(apiUnifiedorderReq.getShippingAddressId());
            makeERJIFENXIAOOrderReq.setProxyId(apiUnifiedorderReqApiReqData.getCookieUserId());
            makeERJIFENXIAOOrderReq.setCardIds(apiUnifiedorderReq.getCardIds());
            makeERJIFENXIAOOrderReq.setOrderType(2);
            HttpResult httpResult =  orderService.makeERJIFENXIAO(makeERJIFENXIAOOrderReq);
            BoProxyOrder boProxyOrder = (BoProxyOrder) httpResult.getData();
            return ApiRespData.buildSucc(packOrderInfo(boProxyOrder));
        } catch (Exception e) {
            LogKit.error(e.getMessage(),e);
            throw new ApiException("下单失败！",0,apiUnifiedorderReqApiReqData.getHead().getCrossDomain());
        }



    }

    /**
     * 订单封装
     * @param boProxyOrder
     * @return
     */
    private ApiOrderInfoResp packOrderInfo(BoProxyOrder boProxyOrder){

        ApiOrderInfoResp apiOrderInfoResp = new ApiOrderInfoResp();
        apiOrderInfoResp.setExpressNumber(boProxyOrder.getOrderExpressNumber());
        apiOrderInfoResp.setExpressCompany(boProxyOrder.getOrderExpressCompany());
        apiOrderInfoResp.setOrderFreight(boProxyOrder.getOrderFreight().toPlainString());
        apiOrderInfoResp.setOrderId(boProxyOrder.getOrderId());
        apiOrderInfoResp.setOrderNumber(boProxyOrder.getOrderNumber());
        apiOrderInfoResp.setOrderPrice(boProxyOrder.getOrderPrice().toPlainString());
        apiOrderInfoResp.setOrderState(boProxyOrder.getOrderPayState()+""+boProxyOrder.getOrderDeliveryState()+""+boProxyOrder.getOrderLockState());
        apiOrderInfoResp.setCreateTime(DateUtil.DateToString(boProxyOrder.getCreateTime(),DateStyle.YYYY_MM_DD_HH_MM_SS));
        /**
         * 转换订单地址
         */
        ApiOrderAddressResp apiAddressInfoResp = new ApiOrderAddressResp();
        apiAddressInfoResp.setAddress(boProxyOrder.getShippingDetailAddress());
        apiAddressInfoResp.setCity(boProxyOrder.getShippingCity());
        apiAddressInfoResp.setConsignee(boProxyOrder.getShippingConsignee());
        apiAddressInfoResp.setCounty(boProxyOrder.getShippingCounty());
        apiAddressInfoResp.setPhone(boProxyOrder.getShippingPhone());
        apiAddressInfoResp.setProvince(boProxyOrder.getShippingProvince());
        apiOrderInfoResp.setShippingAddress(apiAddressInfoResp);

        //获取订单商品
        BoProxyOrderGoodsExample boProxyOrderGoodsExample = new BoProxyOrderGoodsExample();
        boProxyOrderGoodsExample.createCriteria().andOrderIdEqualTo(boProxyOrder.getOrderId());
        List<BoProxyOrderGoods> boProxyOrderGoodses = boProxyOrderGoodsMapper.selectByExample(boProxyOrderGoodsExample);
        List<ApiOrderGoodsResp> list = Lists.newArrayList();
        int number =0;
        if(boProxyOrderGoodses!=null&&boProxyOrderGoodses.size()>0){
            for (BoProxyOrderGoods boProxyOrderGoodse : boProxyOrderGoodses) {
                ApiOrderGoodsResp apiOrderGoodsResp = new ApiOrderGoodsResp();
                apiOrderGoodsResp.setGoodsId(boProxyOrderGoodse.getGoodsId());
                apiOrderGoodsResp.setGoodsImage(boProxyOrderGoodse.getOrderGoodsImage());
                apiOrderGoodsResp.setGoodsNumber(boProxyOrderGoodse.getOrderGoodsNumber().toString());
                apiOrderGoodsResp.setGoodsTitle(boProxyOrderGoodse.getOrderGoodsTitle());
                apiOrderGoodsResp.setGoodsPrice(boProxyOrderGoodse.getOrderGoodsPrice().toPlainString());
                number+=boProxyOrderGoodse.getOrderGoodsNumber();
                String sql = "select o.* from bo_proxy_order_refund_goods g left join bo_proxy_order_refund o on o.order_refund_id= g.order_id where  o.order_id = ? and g.goods_id = ? limit 0,1";
                Map<String,Object> map = ListUtils.getFirst(jdbcTemplate.queryForList(sql,boProxyOrder.getOrderId(),boProxyOrderGoodse.getGoodsId()));
                apiOrderGoodsResp.setCanWanshan(false);
                apiOrderGoodsResp.setCanTuihuo(false);
                apiOrderGoodsResp.setCanCancelRefundGoods(false);
                if(map==null){
                    if(apiOrderInfoResp.isCanRefundGoods()){
                        apiOrderGoodsResp.setCanTuihuo(true);
                        apiOrderGoodsResp.setStateText("");
                    }

                }else{
                    apiOrderGoodsResp.setOrderRefundId(String.valueOf(map.get("order_refund_id")));
                    switch (Integer.parseInt(map.get("order_audit_state").toString())){
                    //    1:正在审核|2:审核通过|3:取消审核|4:审核不通过
                        case 1:
                            apiOrderGoodsResp.setStateText("正在审核");
                            apiOrderGoodsResp.setCanTuihuo(false);
                            apiOrderGoodsResp.setCanCancelRefundGoods(true);
                            break;
                        case 2:
                            apiOrderGoodsResp.setStateText("审核通过");
                            if(map.get("order_express_number")==null||map.get("order_express_number").toString().length()==0){
                                apiOrderGoodsResp.setCanWanshan(true);
                            }else {
                                apiOrderGoodsResp.setStateText("等待系统确认");
                                apiOrderGoodsResp.setOrderRefundId(String.valueOf(map.get("order_refund_id")));
                            }
                            apiOrderGoodsResp.setCanTuihuo(false);
                            break;
                        case 3:
                            apiOrderGoodsResp.setStateText("取消退货");
                            break;
                        case 4:
                            apiOrderGoodsResp.setStateText("审核不通过");
                            apiOrderGoodsResp.setCanTuihuo(false);
                            apiOrderGoodsResp.setCanCancelRefundGoods(true);
                            break;
                        case 5:
                            apiOrderGoodsResp.setStateText("退货完成");
                            apiOrderGoodsResp.setCanTuihuo(false);
                            break;
                    }
                }

                list.add(apiOrderGoodsResp);
            }
        }
        if(apiOrderInfoResp.getOrderState().equals("120")){
            BoCommentExample boCommentExample = new BoCommentExample();
            boCommentExample.createCriteria().andOrderIdEqualTo(boProxyOrder.getOrderId());
            apiOrderInfoResp.setCanComment(boCommentMapper.countByExample(boCommentExample)==0);
        }else{
            apiOrderInfoResp.setCanComment(false);
        }
        apiOrderInfoResp.setOrderGoodsTotal(number);
        apiOrderInfoResp.setOrderDiscountPrice(boProxyOrder.getOrderDiscountPrice().toString());
        apiOrderInfoResp.setOrderFreight(boProxyOrder.getOrderFreight().toString());
        apiOrderInfoResp.setOrderGoodsList(list);
        return apiOrderInfoResp;
    }

    /**
     * 确认收货
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiRespBody> takeOver(ApiReqData<ApiOrderTakeOverReq> apiReqData){

            ApiOrderTakeOverReq apiOrderInfoReq = apiReqData.getBody();
            String orderId = apiOrderInfoReq.getOrderId();
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(orderId);
        if(boProxyOrder.getOrderLockState()==0) {
            boProxyOrder.setOrderLockState(3);
            boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
            orderService.takeOver(orderId);
        } else{
         return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"30001","订单目前处于锁定状态中，暂不支持确认收货！");
        }
        return ApiRespData.buildSucc();
    }

    /**
     * 取消退货申请
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiRespBody> channelRefundGoods(ApiReqData<ApiOrderChannelRefundReq> apiReqData){
        try {
            orderService.auditRefundOrder(apiReqData.getBody().getOrderRefundId(),3);
        } catch (Exception e) {
            return ApiRespData.buildFail();
        }
        return ApiRespData.buildSucc();
    }

    /**
     * 取消订单
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiRespBody> refund(ApiReqData<ApiOrderRefundReq> apiReqData){

        ApiOrderRefundReq apiOrderInfoReq = apiReqData.getBody();
        String orderId = apiOrderInfoReq.getOrderId();
        BoProxyOrder boProxyOrder =  boProxyOrderMapper.selectByPrimaryKey(orderId);
        try {


            if(boProxyOrder.getOrderLockState()==0) {
                if(boProxyOrder.getOrderType()==5){
                    if (boProxyOrder.getOrderPayState() == 0&&boProxyOrder.getOrderDeliveryState() == 0) {
                        BoProxyOrderGoodsExample boProxyOrderGoodsExample = new BoProxyOrderGoodsExample();
                        boProxyOrderGoodsExample.createCriteria().andOrderGoodsIdEqualTo(boProxyOrder.getOrderId());
                        BoProxyOrderGoods first = ListUtils.getFirst(boProxyOrderGoodsMapper.selectByExample(boProxyOrderGoodsExample));
                        if(first!=null){
                            BoTasteGoodsExample boTasteGoodsExample = new BoTasteGoodsExample();
                            boTasteGoodsExample.createCriteria().andBoGoodsIdEqualTo(first.getGoodsId());
                            BoTasteGoods first1 = ListUtils.getFirst(boTasteGoodsMapper.selectByExample(boTasteGoodsExample));
                            if(first1!=null){
                                first1.setBoRemainNum(first1.getBoRemainNum()+1);
                                boTasteGoodsMapper.updateByPrimaryKey(first1);
                            }
                        }
                        boProxyOrder.setOrderLockState(1);
                        boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
                        orderService.quxiao(orderId);
                    }else{
                        throw new ApiException("试吃不允许退款！",0,"10009",apiReqData.getHead().getCrossDomain());
                    }
                }
                HttpResult httpResult = CommonResp.getSuccess();
                if (boProxyOrder.getOrderPayState() == 1) {
                    //订单未发货
                       if (boProxyOrder.getOrderDeliveryState() == 0) {
                            boProxyOrder.setOrderLockState(1);
                            boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
                              httpResult = orderService.refundOrder(orderId, apiReqData.getCookieUserId());
                        } else {
                        /*    boProxyOrder.setOrderLockState(2);
                            boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
                            httpResult = orderService.refundOrderGoods(new OrderRefundModel( apiOrderInfoReq.getOrderGoodsId(),apiOrderInfoReq.getOrderId(),apiOrderInfoReq.getRefundGoodsNumber(),apiReqData.getCookieUserId(), apiOrderInfoReq.getRefundCase(), apiOrderInfoReq.getRefundNotes()));
                           */
                        throw new ApiException("请走退货流程！",0,"10002",apiReqData.getHead().getCrossDomain());
                        }
                } else if (boProxyOrder.getOrderPayState() == 0&&boProxyOrder.getOrderDeliveryState() == 0) {
                    boProxyOrder.setOrderLockState(1);
                    boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
                    httpResult =  orderService.quxiao(orderId);
                } else if (boProxyOrder.getOrderPayState() == 2) {
                    return ApiRespData.buildSucc();
                }
                if(!httpResult.getHttp_status().equals("1")){
                    return  ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,httpResult.getCode(),httpResult.getMessage());
                }
            }else{
                return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"30001","订单目前处于锁定状态中，暂不支持取消操作！");
            }
            return ApiRespData.buildSucc();
        } catch (Exception e) {
            LogKit.error(e.getMessage(),e);
            boProxyOrder.setOrderLockState(0);
            boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
            throw new ApiException("取消订单失败！",0,apiReqData.getHead().getCrossDomain());
        }

    }

    /**
     * 退货申请
     * @param apiReqData
     * @return
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<ApiRespBody> refundGoodsApply(ApiReqData<ApiOrderRefundReq> apiReqData){

        ApiOrderRefundReq apiOrderInfoReq = apiReqData.getBody();
        String orderId = apiOrderInfoReq.getOrderId();
        BoProxyOrder boProxyOrder =  boProxyOrderMapper.selectByPrimaryKey(orderId);
        try {



            if(boProxyOrder.getOrderLockState()==0) {
                HttpResult httpResult = CommonResp.getSuccess();
                if (boProxyOrder.getOrderPayState() == 1) {
                    //订单已发货
                    if (boProxyOrder.getOrderDeliveryState() == 1) {
                            boProxyOrder.setOrderLockState(2);
                            boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
                            httpResult = orderService.refundOrderGoods(new OrderRefundModel( apiOrderInfoReq.getOrderId(),apiOrderInfoReq.getOrderGoodsId(),apiOrderInfoReq.getRefundGoodsNumber(),apiReqData.getCookieUserId(), apiOrderInfoReq.getRefundCase(), apiOrderInfoReq.getRefundNotes(),apiOrderInfoReq.getVoucher()));
                        return ApiRespData.buildSucc();
                    }
                }
                if(!httpResult.getHttp_status().equals("1")){
                    return  ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,httpResult.getCode(),httpResult.getMessage());
                }
            }else{
                return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,"30001","订单目前处于锁定状态中，暂不支持取消操作！");
            }
            return ApiRespData.buildFail();
        } catch (ApiException e) {
            boProxyOrder.setOrderLockState(0);
            boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
            throw e;
        }catch (Exception e) {
            boProxyOrder.setOrderLockState(0);
            boProxyOrderMapper.updateByPrimaryKey(boProxyOrder);
            LogKit.error(e.getMessage(),e);
            throw new ApiException("退货操作失败,请重试或联系客服！",0,apiReqData.getHead().getCrossDomain());
        }

    }

    /**
     * 调起微信二维码支付
     * @param apiOrderInfoReqApiReqData
     */
    @AuthAnnotation(iLogin = true)
    public void payByQrcodeWx(ApiReqData<ApiOrderInfoReq> apiOrderInfoReqApiReqData){
        HttpServletResponse response = apiOrderInfoReqApiReqData.getHead().getHttpServletResponse();
        OutputStream outputStream = null;
            try {
                ApiOrderInfoReq apiUnifiedorderReq = apiOrderInfoReqApiReqData.getBody();
                String orderId = apiUnifiedorderReq.getOrderId();
                BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(orderId);
                if (boProxyOrder != null && boProxyOrder.getOrderPayState() == 0) {
                    BoProxyOrderGoodsExample boProxyOrderGoodsExample = new BoProxyOrderGoodsExample();
                    boProxyOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
                    BoProxyOrderGoods boProxyOrderGoods = ListUtils.getFirst(boProxyOrderGoodsMapper.selectByExample(boProxyOrderGoodsExample));
                    UnifiedOrderReqData unifiedOrderReqData = new UnifiedOrderReqData(boProxyOrder.getOrderNumber(),  boProxyOrderGoods.getOrderGoodsTitle(), boProxyOrderGoods.getOrderGoodsTitle(), boProxyOrder.getOrderNumber(), boProxyOrder.getOrderPrice().multiply(new BigDecimal(100)).intValue(), "WEB", "HH");
                    System.out.println("========================="+JSON.toJSONString(unifiedOrderReqData));
                    UnifiedOrderRespData unifiedOrderRespData = WXPay.doUnifiedOrderBusiness(unifiedOrderReqData);
                    if (!unifiedOrderRespData.getResult_code().equals("SUCCESS")) {
                        throw new ApiException("微信下单失败",0,apiOrderInfoReqApiReqData.getHead().getCrossDomain());
                    } else {
                        String url = unifiedOrderRespData.getCode_url();
                        outputStream = response.getOutputStream();
                        String format = "png";// 图像类型
                        Map<EncodeHintType, Object> hints = Maps.newHashMap();
                        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 200, 200, hints);
                        MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);// 输出图像
                    }

                }} catch (IOException e) {
                LogKit.error(e.getMessage(),e);
                throw new ApiException(e.getMessage(),0,apiOrderInfoReqApiReqData.getHead().getCrossDomain());
            } catch (WriterException e) {
                LogKit.error(e.getMessage(),e);
                throw new ApiException(e.getMessage(),0,apiOrderInfoReqApiReqData.getHead().getCrossDomain());
            } catch (Exception e) {
                LogKit.error(e.getMessage(),e);
                throw new ApiException(e.getMessage(),0,apiOrderInfoReqApiReqData.getHead().getCrossDomain());
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.flush();
                        outputStream.close();
                    }
                } catch (IOException e) {
                    LogKit.error(e.getMessage());
                }
            }
    }



    /**
     * 调起jsApi支付
     * @param code
     * @param state
     * @param orderId
     * @return
     */
    public JsApiPayModel wxJsApi(String code, String state, String orderId) {
        System.out.println(new Date().getTime()+"第一次加载..............");
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(orderId);
        if (boProxyOrder != null && boProxyOrder.getOrderPayState() == 0) {
            try {
                BoProxyOrderGoodsExample boProxyOrderGoodsExample = new BoProxyOrderGoodsExample();
                boProxyOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
                JSONObject snsParam = null;
                if(CacheKit.get("wxloginTokenEx",orderId+code)!=null){
                    snsParam = CacheKit.get("wxloginTokenEx",orderId+code);
                }else{
                    snsParam = wxService.getSnsParam(code);
                    CacheKit.put("wxloginTokenEx",orderId+code,snsParam);
                }

                String openId = "";
                if(snsParam!=null){
                    openId = snsParam.getString("openid");
                }else{
                    throw new ApiException("微信下单失败:openId获取失败！"+JSON.toJSONString(snsParam) ,0,"40001","crossDomain");
                }
                BoProxyOrderGoods boProxyOrderGoods = ListUtils.getFirst(boProxyOrderGoodsMapper.selectByExample(boProxyOrderGoodsExample));
                UnifiedOrderReqData unifiedOrderReqData = new UnifiedOrderReqData(boProxyOrder.getOrderNumber(),  boProxyOrderGoods.getOrderGoodsTitle(), boProxyOrderGoods.getOrderGoodsTitle(), boProxyOrder.getOrderNumber(), boProxyOrder.getOrderPrice().multiply(new BigDecimal(100)).intValue(), "WEB", "ZC", "JSAPI", openId);
                UnifiedOrderRespData unifiedOrderRespDate = WXPay.doUnifiedOrderBusiness(unifiedOrderReqData);
                if(!unifiedOrderRespDate.getResult_code().equals("SUCCESS")){
                    throw new ApiException("微信下单失败:！"+unifiedOrderRespDate.getErr_code_des(),0,"40001","crossDomain");
                }
                JsApiPayModel jsApiPayModel = new JsApiPayModel("prepay_id=" + unifiedOrderRespDate.getPrepay_id() + "");
                return jsApiPayModel;
            } catch (IOException e) {
                LogKit.error(e.getMessage(),e);
                throw new ApiException("请求微信授权出错！",0,"40001","crossDomain");
            } catch (Exception e) {
                LogKit.error(e.getMessage(),e);
                throw new ApiException("微信下单失败！",0,"40002","crossDomain");
            }
        }else{
            throw new ApiException("订单异常，请尝试重新下单！",0,"40000","crossDomain");
        }

    }
   /* public JsApiPayModel wxXcxApi(String code, String orderId) {
        BoProxyOrder boProxyOrder = boProxyOrderMapper.selectByPrimaryKey(orderId);
        if (boProxyOrder != null && boProxyOrder.getOrderPayState() == 0) {
            try {
                BoProxyOrderGoodsExample boProxyOrderGoodsExample = new BoProxyOrderGoodsExample();
                boProxyOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
                BoProxyOrderGoods boProxyOrderGoods = ListUtils.getFirst(boProxyOrderGoodsMapper.selectByExample(boProxyOrderGoodsExample));
                String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxde058a88e81e820f&secret=aedbe54587aa0233eb00a74bdb96867e&js_code="+code+"&grant_type=authorization_code";
                String json = OkHttpUtil.get(url);
                JSONObject g= JSON.parseObject(json);
                LogKit.info(g.toJSONString()+"------------------------------------");
                UnifiedOrderReqData unifiedOrderReqData = new UnifiedOrderReqData(boProxyOrder.getOrderNumber(),  "斑斑-"+boProxyOrderGoods.getOrderGoodsTitle(), boProxyOrderGoods.getOrderGoodsTitle(), boProxyOrder.getOrderNumber(), boProxyOrder.getOrderPrice().multiply(new BigDecimal(100)).intValue(), "WEB", "ZC", "JSAPI", g.getString("openid"),"wxde058a88e81e820f");
                LogKit.info(JSON.toJSONString(unifiedOrderReqData)+"------------------------------------");
                UnifiedOrderRespData unifiedOrderRespDate = WXPay.doUnifiedOrderBusiness(unifiedOrderReqData);
                if(!unifiedOrderRespDate.getResult_code().equals("SUCCESS")){
                    throw new ApiException(0,"40001","微信下单失败:！"+unifiedOrderRespDate.getErr_code_des());
                }
                JsApiPayModel jsApiPayModel =   new JsApiPayModel("prepay_id=" + unifiedOrderRespDate.getPrepay_id() + "","wxde058a88e81e820f");
                return jsApiPayModel;
            } catch (IOException e) {
                LogKit.error(e.getMessage(),e);
                throw new ApiException(0,"40001","请求微信授权出错！");
            } catch (Exception e) {
                LogKit.error(e.getMessage(),e);
                throw new ApiException(0,"40002","微信下单失败！");
            }
        }else{
            throw new ApiException(0,"40000","订单异常，请尝试重新下单！");
        }

    }*/

    /**
     * 微信支付回调
     * @param request
     */
    public void orderWxPayCallBack(HttpServletRequest request){
        DataInputStream in = null;
        String wxNotifyXml = "";
        try {
            in = new DataInputStream(request.getInputStream());
            int il=request.getContentLength();
            if(il!=0){
                byte[] byteData = new byte[il];
                in.readFully(byteData);
                in.close();
                wxNotifyXml = new String(byteData);
                LogKit.info("支付回调+"+wxNotifyXml);
                Map<String, Object> resault = XMLParser.getMapFromXML(wxNotifyXml);
                String result_code=resault.get("result_code").toString();
                String return_code=resault.get("return_code").toString();
                //第一:判断请求参数是否正确
                if("SUCCESS".equals(return_code)){
                    //第二:判断订单是否能找到
                    if("SUCCESS".equals(result_code)){
                        boolean istrue= Signature.checkIsSignValidFromResponseString(wxNotifyXml);
                        if(istrue){
                            //处理支付成功回调
                            orderService.paySuccess(resault);
                        }

                    }
                }
            }
        } catch (Exception e) {
            LogKit.error(e.getMessage(),e);
            LogKit.error(e.getMessage());
        }finally{
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                LogKit.error(e.getMessage());
            }
        }
    }
    /**
     * 订单日志
     */
    public ApiRespData<List<ApiOrderLogResp>> orderInfoLog(ApiReqData<ApiOrderInfoReq> apiReqData){
            ApiOrderInfoReq apiUnifiedorderReq = apiReqData.getBody();
                String orderId = apiUnifiedorderReq.getOrderId();
                BoOrderLogExample boOrderLogExample = new BoOrderLogExample();
                boOrderLogExample.createCriteria().andOrderIdEqualTo(orderId);
                boOrderLogExample.setOrderByClause("order_log_create_time desc");
                List<BoOrderLog> boOrderLogs = boOrderLogMapper.selectByExample(boOrderLogExample);
                List<ApiOrderLogResp> list = Lists.newArrayList();
                if(boOrderLogs!=null){
                    for (BoOrderLog boOrderLog : boOrderLogs) {
                        ApiOrderLogResp apiOrderLogResp = new ApiOrderLogResp();
                        apiOrderLogResp.setMessage(boOrderLog.getOrderLogMessage());
                        apiOrderLogResp.setTime(DateUtil.DateToString(boOrderLog.getOrderLogCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
                        list.add(apiOrderLogResp);
                    }
                }
                return ApiRespData.buildSucc(list);

    }
}
